package org.model.controller;

import cn.hutool.json.JSONUtil;
import com.alibaba.nacos.shaded.org.checkerframework.checker.units.qual.C;
import lombok.extern.log4j.Log4j;
import org.jetbrains.annotations.NotNull;
import org.model.service.BigModel;
import org.model.service.BigModelImpl.BigModelImpl;
import org.model.service.modelListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@Log4j
@ServerEndpoint("/model/talk/{UUID}")
public class BigModelController {

    /**
     * 线程安全的无序的集合
     */
    private static final CopyOnWriteArraySet<Session> SESSIONS = new CopyOnWriteArraySet<>();

    /**
     * 存储在线连接数
     */
    private static final Map<String, Session> SESSION_POOL = new HashMap<>();

    private static BigModel bigModel;

    @Autowired
    public void setBigModel(BigModel bigModel) {
        BigModelController.bigModel = bigModel;
    }

    @OnOpen
    /**
     * WebSocket类，处理WebSocket连接和消息
     */
    public void onOpen(Session session, @PathParam(value = "UUID") String userId) {
        try {

            SESSIONS.add(session); // 将新的会话添加到SESSIONS集合中
            SESSION_POOL.put(userId, session); // 将用户ID和会话添加到SESSION_POOL中
            log.info("【WebSocket消息】有新的连接，总数为：" + SESSIONS.size()); // 打印新连接的数量
        } catch (Exception e) {
            e.printStackTrace(); // 打印异常堆栈信息
        }
    }

    @OnClose
    public void onClose(Session session,@PathParam(value = "UUID") String userId) {
        try {
            SESSIONS.remove(session);
            log.info("【WebSocket消息】连接断开，总数为：" + SESSIONS.size());
//            BigModelImpl.currentSocket.get(userId).close(1000, "");
//            BigModelImpl.currentSocket.remove(userId);
            modelListener.historyList.remove(userId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnMessage
    public void onMessage(@NotNull String message, @PathParam(value = "UUID") String userId) {
        bigModel.talk(message, userId);
    }


    /**
     * 此为单点消息
     *
     * @param userId  用户编号
     * @param message 消息
     */
    public void sendOneMessage(String userId, String message) {
        Session session = SESSION_POOL.get(userId);
        if (session != null && session.isOpen()) {
            try {
                synchronized (session) {
                    log.info("【WebSocket消息】单点消息：" + message);
                    session.getAsyncRemote().sendText(message);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 配置错误信息处理
     * @param session
     * @param t
     */
    @OnError
    public void onError(Session session, Throwable t) {
        //什么都不想打印都去掉就好了
        log.info("【websocket消息】出现未知错误 ");
        //打印错误信息，如果你不想打印错误信息，去掉就好了
        //这里打印的也是  java.io.EOFException: null
        t.printStackTrace();
    }

}
